import BrowserService from '../../browser.service';
import { AddTemplateConfigEntity } from '../../config';
import { consoleLog, delay } from '../../utils';

export default class AddTemplateController extends BrowserService {
  public templateConfig: AddTemplateConfigEntity;
  constructor(templateConfig: AddTemplateConfigEntity) {
    super();
    this.templateConfig = templateConfig;
  }
  async init() {
    await this.exportConfig(
      this.templateConfig.title,
      this.templateConfig.from
    );
    if(this.templateConfig.btnGroup) {
      await this.clickGroup(this.templateConfig.btnGroup);
    } else {
      await this.page.goto(this.templateConfig.pageUrl, {
        waitUntil: 'networkidle',
      });
    }
    await this.openAddDialog();
  }
  async openAddDialog() {
    await this.page.click(this.templateConfig.operation.selector);
    await delay(4000);
    const isVisible = await this.page.isVisible(
      `.dialog-title:has-text("${this.templateConfig.dialogTitle}")`
    );
    const isFormVisible = await this.page.isVisible('.thy-form');
    if (isVisible && isFormVisible) {
      await this.addProject();
    } else {
      console.log('弹框加载失败');
    }
  }
  async addProject() {
    await this.submitForm(this.templateConfig.from);
    const fromDataState = await this.expectFormData(this.templateConfig.from);
    if (fromDataState) {
      await this.expectProject();
    }
  }
  async expectProject() {
    const isVisible = await this.page.isVisible(
      `.dialog-title:has-text("${this.templateConfig.dialogTitle}")`
    );
    const isNotify = await this.page.isVisible('.thy-notify-content');
    // 弹框消失证明添加成功
    if (isNotify && !isVisible) {
      const errText = await this.page.innerText('.thy-notify-content span');
      await consoleLog(`${this.templateConfig.title} ${errText}`, this.logPath);
    } else {
      if(this.templateConfig.testPage.pageUrl) {
        await this.page.goto(this.templateConfig.testPage.pageUrl, {
          waitUntil: 'networkidle',
        });
      }
      if(this.templateConfig.testPage.btnGroup) {
        await this.clickGroup(this.templateConfig.testPage.btnGroup);
      }
      await this.expectTableTestResult(this.templateConfig.testPage.table);
    }
    await this.screenshot(this.templateConfig.screenshotName);
  }
}

/**
 * 创建模板脚本[针对创建表单+table验证]
 * 2. 点击新建测试库按钮出现创建测试库弹框
 * 3. 输入表单内容
 * 4. 点击保存按钮
 * 5. 数据列表
 * 6. 比对列表上的内容是否正确[选择按照时间排序]
 */
